﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using Site3AI.Models;

namespace M3AI.Services
{
    public class _SiteBaseController : Controller
    {
        public DateTime Now {
            get {
                return MvcApplication.Now;
            }
        }
        protected Site3AIEntities _db;
        public Site3AIEntities DB
        {
            get
            {
                if (null == _db)
                {
                    _db = new Site3AIEntities();
                }
                return _db;
            }
        }

        protected Services _svc;
        public Services Services
        {
            get
            {
                if (null == _svc)
                {
                    _svc = new Services() { DB = this.DB, SiteUser = SiteUser, ControllerContext = this };
                }
                return _svc;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (null != _db) _db.Dispose();
            base.Dispose(disposing);
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (Request.IsAuthenticated)
            {
                ReLoadSiteUser();
            }
        }

        public void ReLoadSiteUser()
        {
            SiteUser = DB.aspnet_Users.Where(v => v.LoweredUserName == User.Identity.Name.ToLower()).FirstOrDefault();
            //ViewBag.SiteUser = SiteUser;
        }
        public aspnet_Users SiteUser
        {
            get { return ViewBag.SiteUser; }
            set
            {
                ViewBag.SiteUser = value;
            }
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //if(Request.IsAuthenticated){
            //    var u = DB.aspnet_Users.Where(v => v.LoweredUserName == User.Identity.Name.ToLower()).FirstOrDefault();
            //    ViewBag.SiteUser = u;
            //}
            base.OnActionExecuting(filterContext);
        }

        protected ActionResult ViewOrPartial(object model, string viewname = null)
        {
            bool IsView = string.IsNullOrEmpty(Request["IsView"]) ? true : bool.Parse(Request["IsView"]);
            if (IsView) return View(viewname, model);
            else return PartialView(viewname, model);
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception is SiteException)
            {
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.Result = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "text/json", Data = new { error = filterContext.Exception.Message } };

                filterContext.HttpContext.Response.StatusCode = 500;
                filterContext.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                filterContext.HttpContext.Response.StatusDescription = "Site Action Exception";

            }
            //else if (filterContext.Exception is System.Data.UpdateException
            //    && filterContext.Exception.InnerException != null
            //    && filterContext.Exception.InnerException is System.Data.SqlClient.SqlException
            //    && filterContext.Exception.InnerException.Message.StartsWith("DELETE")
            //    && filterContext.Exception.InnerException.Message.Contains("REFERENCE"))
            //{
            //    filterContext.ExceptionHandled = true;
            //    filterContext.HttpContext.Response.Clear();
            //    filterContext.Exception = new System.Data.UpdateException("要删除数据已经被使用，需要删除使用此数据的内容后才能删除此数据。", filterContext.Exception);
            //    filterContext.Result = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "text/json", Data = new { error = filterContext.Exception.Message } };

            //    filterContext.HttpContext.Response.StatusCode = 500;
            //    filterContext.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    filterContext.HttpContext.Response.StatusDescription = "Site Action Exception";

            //}
            else
            {

                base.OnException(filterContext);
            }
        }
    }

    public class SiteIdentity : IIdentity
    {
        public string Title { get; private set; }
        public string ID { get; private set; }
        public SiteIdentity(string id, string title)
        {
            Title = title; ID = id;
        }


        public string AuthenticationType
        {
            get { return "SiteIdentity"; }
        }

        public bool IsAuthenticated
        {
            get { return string.IsNullOrEmpty(ID); }
        }

        public string Name
        {
            get { throw new System.NotImplementedException(); }
        }
    }
    public class SitePrincipal : IPrincipal
    {

        public IIdentity Identity { get; private set; }
        public SitePrincipal(SiteIdentity identity)
        {
            Identity = identity;
        }
        public bool IsInRole(string role)
        {
            if (Identity.IsAuthenticated == false) return false;
            else
            {
                return true;
            }
        }
    }

    public class SiteException : Exception
    {
        public SiteException() { }
        public SiteException(string p) : base(p) { }

    }
}
